package com.zymail.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zymail.bean.*;
import com.zymail.entity.WxPayNotifyV0;
import com.zymail.service.*;
import com.zymail.service.impl.WxPayService;
import com.zymail.wxpay.WXPayUtil;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/money")
public class MoneyController extends BaseController {
    @Autowired
    ZyMoneyService moneyService;

    @Autowired
    ZyBusService busService;

    @Autowired
    ZyOrderService orderService;

    @Autowired
    ZyConService conService;

    @Autowired
    WxPayService payService;

    @Autowired
    ZyUserService userService;

    /**
     * 购物车/常规 支付api
     * @param request   request
     * @param session_key   session_key
     * @param orderList 订单列表
     * @return  加密后的支付消息
     * @throws Exception    未知异常
     */
    @PostMapping("/createMoney/{session_key}")
    public Map<String, String> createMoney(HttpServletRequest request,
                                           @PathVariable("session_key") String session_key,
                                           @RequestBody List<ZyOrder> orderList) throws Exception {
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        ZyMoney money = new ZyMoney(null, 0d, null, 0, LocalDateTime.now());
        moneyService.save(money);

        int moneyId = money.getId();
        Double sum = 0d;

        for (ZyOrder order: orderList) {
            order.setUserId(userId);
            order.setTime(LocalDateTime.now());
            order.setFlag(2);
            sum += order.getPrice();
            orderService.save(order);
            conService.save(new ZyCon(null, moneyId, order.getId()));
        }

        System.out.printf("moneyfee : " + sum);
        money.setFee(sum);
        moneyService.updateById(money);


        //获得请求ip地址
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        if(ip.contains(",")){
            String[] ips = ip.split(",");
            ip = ips[0].trim();
        }

        return payService.wxPay(userId, ip, money.getId());
    }

    /**
     * 支付失败后再支付
     * @param request   request
     * @param session_key   session_key
     * @param orderId   重支付的id
     * @return  加密过后的支付map
     * @throws Exception    未知Expection
     */
    @PostMapping("/repay/{session_key}/{orderId}")
    public Map<String, String> repay(HttpServletRequest request,
                                     @PathVariable("session_key") String session_key,
                                     @PathVariable("orderId") Integer orderId) throws Exception {
        Integer userId = get_userId(session_key);
        if(userId == 0) return null;

        ZyMoney money = new ZyMoney(null, 0d, null, 0, LocalDateTime.now());
        moneyService.save(money);

        int moneyId = money.getId();
        Double sum = 0d;

        ZyOrder order = orderService.getById(orderId);
        order.setFlag(2);
        order.setFloor(null);
        order.setUser(null);
        order.setGoodDe(null);
        sum += order.getPrice();
        orderService.updateById(order);
        conService.save(new ZyCon(null, moneyId, order.getId()));

        money.setFee(sum);

        moneyService.updateById(money);

        //获得请求ip地址
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        if(ip.contains(",")){
            String[] ips = ip.split(",");
            ip = ips[0].trim();
        }

        return payService.wxPay(userId, ip, moneyId);
    }

    /**
     * 支付成功回调函数
     * @param request   request对象
     * @param param 支付回调结果
     * @return  xml文件
     * @throws Exception    未知错误
     */
    @RequestMapping(value = "/wxPay/success", produces = MediaType.TEXT_PLAIN_VALUE)
    public String success(HttpServletRequest request, @RequestBody WxPayNotifyV0 param) throws Exception{
        Map<String, String> result = new HashMap<>();
        System.out.println("回调res : = " + param);
        if ("SUCCESS".equals(param.getReturn_code())){
            String trade_no = param.getOut_trade_no();

            QueryWrapper<ZyMoney>  moneyWrapper = new QueryWrapper<>();
            moneyWrapper.eq("trade_no", trade_no);
            ZyMoney money = moneyService.getOne(moneyWrapper);
            money.setStatus(1); //付款成功
            moneyService.updateById(money);

            QueryWrapper<ZyCon> conWrapper = new QueryWrapper<>();
            conWrapper.eq("money_id", money.getId());
            List<ZyCon> zyCons = conService.list(conWrapper);

            for (ZyCon con: zyCons) {
                ZyOrder order = orderService.getById(con.getOrderId());
                order.setFlag(3);
                order.setGoodDe(null);
                order.setFloor(null);
                order.setUser(null);
                orderService.updateById(order);
            }

            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
        }
        return WXPayUtil.mapToXml(result);
    }


    @RequestMapping("/test")
    public void test() throws Exception {
        payService.wxrePay(44, 217, 0.5);
    }
}
